Skip to content

Support MRL (Matryoshka Representation Learning) #676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 23, 2025

Conversation

kozistr
Copy link
Contributor

@kozistr kozistr commented Jul 4, 2025

What does this PR do?

Fixes #673

Add dimensions field to the embed request API spec.

  • compatible with OpenAI client
  • both http & grpc
  • add a test case for the MRL feature
  • remove the unused test cases in router/tests
$ ./target/release/text-embeddings-router --model-id ../Qwen3-Embedding-0.6B/ --pooling last-token --port 8080 --dtype float32 --auto-truncate --max-batch-tokens 512
from openai import OpenAI

client = OpenAI(api_key='', base_url='http://127.0.0.1:8080')

response = client.embeddings.create(
    model='Qwen3-Embedding-0.6B',
    input='test',
    dimensions=256,
)

len(response.data[0].embedding)
256
tei_results = np.asarray(
    requests.post(
        'http://127.0.0.1:8080/embed',
        data=json.dumps({'inputs': sentences[0], 'normalize': True, 'dimensions': 256}),
        headers={'Content-type': 'application/json'},
    ).json()
)
tei_results.shape
(1, 256)

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline,
    Pull Request section?
  • Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the
    documentation guidelines, and
    here are tips on formatting docstrings.
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@Narsil @alvarobartt

@kozistr kozistr changed the title Support MRL (Matryoshka Representation Learning Support MRL (Matryoshka Representation Learning) Jul 4, 2025
@kozistr kozistr marked this pull request as ready for review July 4, 2025 15:22
alvarobartt
alvarobartt previously approved these changes Jul 8, 2025
Copy link
Member

@alvarobartt alvarobartt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for the addition! Also I like the macros for Prometheus metrics, those look cleaner IMO.

P.S. Guessing that the snapshots were removed because those were not used, right?

Co-authored-by: Alvaro Bartolome <[email protected]>
@kozistr
Copy link
Contributor Author

kozistr commented Jul 9, 2025

LGTM, thanks for the addition! Also I like the macros for Prometheus metrics, those look cleaner IMO.

P.S. Guessing that the snapshots were removed because those were not used, right?

oh, sorry for the missing context. you're right!

looks like these test cases (router/tests) were all commented, so I've removed the snapshots.

updated)
I've just updated the PR description too!

thanks for the pointing this :)

alvarobartt
alvarobartt previously approved these changes Jul 9, 2025
@michaelfeil
Copy link
Contributor

@kozistr QQ: what happens if you set normalize=True + mrl dimensions? Otherwise PR looks good.

@kozistr
Copy link
Contributor Author

kozistr commented Jul 15, 2025

@kozistr QQ: what happens if you set normalize=True + mrl dimensions? Otherwise PR looks good.

@michaelfeil Hi! MRL will always run first before the normalization! (+ normalize is True as a default value)

thanks for double-checking this :)

@michaelfeil
Copy link
Contributor

Is there something bringing this to mainline?

Comment on lines 297 to 304
metrics::counter!("te_embed_success").increment(1);
metrics::histogram!("te_embed_duration").record(total_time.as_secs_f64());
metrics::histogram!("te_embed_tokenization_duration")
.record(response.metadata.tokenization.as_secs_f64());
metrics::histogram!("te_embed_queue_duration")
.record(response.metadata.queue.as_secs_f64());
metrics::histogram!("te_embed_inference_duration")
.record(response.metadata.inference.as_secs_f64());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you revert those changes ? They don't seem linked to the PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reverted 9131071

permit: OwnedSemaphorePermit,
) -> Result<PooledEmbeddingsInferResponse, TextEmbeddingsError> {
let start_time = Instant::now();

if self.is_splade() && normalize {
let counter = metrics::counter!("te_request_failure", "err" => "model_type");
counter.increment(1);
metrics::counter!("te_request_failure", "err" => "model_type").increment(1);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sam here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reverted 9131071

let message = "`normalize` is not available for SPLADE models".to_string();
tracing::error!("{message}");
return Err(TextEmbeddingsError::Backend(BackendError::Inference(
message,
)));
}

if let Some(dimensions) = dimensions {
if dimensions == 0 {
metrics::counter!("te_request_failure", "err" => "validation").increment(1);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't they also be smaller than the maximum embedding dimension ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At that time, I was considering silently returning the embedding with the original size when the given dimension is larger than the expected size, like line 274.

On second thought, like you mentioned, it'd be better to raise an error explicitly when the size is larger than expected in terms of validity.

I'll add an extra validation logic to check whether the given size is larger than the size of the embedding. thanks for catching this!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added a1b1a26

Copy link
Collaborator

@Narsil Narsil left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM !

@Narsil Narsil merged commit 45df4fa into huggingface:main Jul 23, 2025
@kozistr kozistr deleted the feature/mrl branch July 23, 2025 16:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature: Support Matryoshka Representation Learning
4 participants